
/*
 * @Author: 简佳成
 * @Date: 2019-12-17 10:02:54
 * @LastEditTime : 2020-02-05 18:01:25
 * @LastEditors  : Please set LastEditors
 * @Description: 签章图片上传页面
 * @FilePath: \Electronic_Seal_Mobile\src\pages\UploadImg\index.js
 */

import React, { Component } from 'react';
import { connect } from 'dva';
import {
  ImagePicker,
  Modal,
  NavBar,
  List,
  InputItem,
  Icon,
  Picker,
  Button,
  WhiteSpace,
  Toast,
  Flex,
} from 'antd-mobile';
import { createForm } from 'rc-form';
import router from 'umi/router';
import { sealSize,ENTER_TYPE } from 'utils/Enum.js';
import MyNavBar from '../../components/navbar/index';
import ErrorMsg from '../../components/form-error-msg/index';
import {MyIcon} from '../../components/my-icon/index';
import styles from './index.less'
import { checkUrl, getIsDingTalk, backToOut, recordEnterHistoryNum } from '../../utils/utils';
import commonStyles from 'utils/common.less';


const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
const alert = Modal.alert;
// if (isIPhone) {
//   moneyKeyboardWrapProps = {
//     onTouchStart: e => e.preventDefault(),
//   };
// }

@connect(({ upImgModel,loading }) => ({
  upImgModel,
  loading,
  loadingUpdate: loading.models.upImgModel,
}))
class ImagePickerExample extends Component {
  constructor(props) {
    super(props);
    const {
      location: { params },
    } = props;
    this.state = {
      isDisabled: true,
      files: params&&params.fileData&&params.fileData.url ? [params.fileData] : [],
      visibleType: false,
      size: '25vhx25vh',
      sealName:''
    };
  }

  /**
   * @description 上传文件后用以获取数据和跳转页面
   * @param {*} files 回调拿到的图片文件
   * @param {*} type
   * @param {*} index
   */
  onChange = (files, type, index) => {
    const { getFieldsValue } = this.props.form;
    const { location:{query},dispatch } = this.props;
    const formValue = getFieldsValue(['name', 'size']);
    if (files[0]) {
      const {file:{size}} = files[0]
      if(size > 10*1024*1024) {
        Toast.fail('图片太大,请更换图片')
        return
    }
    //  TODO:用model传值，而不是路由感觉要简单一点
      router.replace({
        pathname: '/EditImg',
        query:query,
        params: {
          fileData: files[0],
          formValue: formValue,
        },
      });
      dispatch({
          type:'upImgModel/saveDefaultImg',
          payload:{
            defaultImg:files[0].url
          }
      })
    }
    this.setState({
      files,
    });
  };

  handleClick = () => {
    this.inputRef.focus();
  };

  handleDelImg = () => {
    const {dispatch} = this.props
    this.setState({
      files: [],
    });
    dispatch({
      type:'upImgModel/delDefaultImg',
      payload:{
        defaultImg:''
      }
  })
  };


  /**
   * @description 重新裁剪图片
   */
  handleReCorp = () => {
    const { getFieldsValue } = this.props.form;
    const { location:{query,params}} = this.props;
    const { files } = this.state;
    const formValue = getFieldsValue(['name', 'size']);
    router.replace({
      pathname: '/editImg',
      query:query,
      params: {
        fileData: files[0],
        restoreData: params.baseData,
        formValue: formValue,
        reCorp:true
      },
    });
  };

  /**
   * @description 编辑页面可跳转到本页，所以需要初始化图像和表单
   * @memberof ImagePickerExample
   * @params 路由参数
   * @setFieldsValue 重置表单值的函数
   */
  componentDidMount() {
    const { setFieldsValue } = this.props.form;
    const {
      location: { params ,query},
    } = this.props;
    if(!checkUrl(query)){
      alert('警告', '无法操作！', [
        { text: '返回', onPress: () =>backToOut() },
      ])
    }
    if (params) {
      if (params.formValue) {
        const { formValue } = params;
        setFieldsValue({
          ...formValue,
        });
        this.setState({
          size: formValue.size[0],
          sealName:formValue.name
        });
      }
    }

    const isEnterPage=localStorage.getItem('isEnterPage')||'yes';
    if(isEnterPage==='yes'){
      recordEnterHistoryNum();
    }
  }

  handleValidate = () => {
    const { validateFields } = this.props.form;
    const { files } = this.state;
    validateFields((error, values) => {
      if (!error && files[0]) {
        const {dispatch} = this.props
        const [width,height] = values.size[0].split('x')
        dispatch({
          type:'upImgModel/upImg',
          payload:{
            from:'IMAGE_CREATED',
            name:values.name,
            dimension:JSON.stringify({
              width: width,
              height: height
              },),
            base64:files[0].url.replace(/^data:image\/\w+;base64,/, "")
          },
          callback: (state, msg) => {
            if(state === 'success') {
                Toast.success(msg,2,null,false)
              const { location: { query: { popType } } } = this.props;
              let enterType = localStorage.getItem('enterType')
                if(enterType==ENTER_TYPE.EXTERNAL){
                  // backToOut();
                  window.location.href=localStorage.getItem('returnUrl')
                }else{
                  router.push({pathname:'/Signature',params:{type:popType}})
                }

            } else {
                Toast.fail(msg,2,null,false)
            }
        }
        })
      } else {
        Toast.fail('请填写正确信息');
      }
    });
  };

  handleSizeChange = value => {
    this.setState({
      size: value[0],
    });
  };

  handleInputChange = value =>{
    this.setState({
      sealName: value,
    });
  }

  render() {
    const { files, size='25vhx25vh',sealName } = this.state;
    const [x, y] = size.split('x').map(val => {
      if (val.indexOf('vh') == -1) {
        return val + 'mm';
      } else {
        return val;
      }
    });
    const formData = { formData };
    const { getFieldProps, getFieldDecorator } = this.props.form;
    const { loadingUpdate } = this.props;
    let enterType = localStorage.getItem('enterType')
    let url=''
    url = enterType==ENTER_TYPE.EXTERNAL?'':'/Signature'
    const isDingTalk=getIsDingTalk();
    // const contentContainer=commonStyles.headerTop;
    const contentContainer=isDingTalk==='true'?styles.btnMargin:commonStyles.headerTop;

    let isExternal=false
    if(enterType==ENTER_TYPE.EXTERNAL){
      isExternal=true
    }
    return (
      <div style={{ width: '100vw', height: '100vh' ,overflow:'hidden'}}>
        <MyNavBar title={'上传用印图片'} backUrl={url} isExternal={isExternal}/>
        <div className={styles.center+' '+contentContainer}>
        <div style={{background:'rgba(242,244,245,1)',height:'1.5vh'}}></div>
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              width: '100vw',
              height: '40vh',
              minHeight:y,
            }}
          >
            <div
              className="myUpImgBox"
              style={{
                width: x,
                height: y,
                position: 'relative',
                outline: files[0] ? '2px dashed #108ee9' : '',
              }}
            >
              {files[0] && (
                <Icon
                  type="iconClose"
                  style={{ position: 'absolute', left: -12, top: -12, zIndex: 1,fontSize:22,width:22,height:22 }}
                  onClick={() =>
                    alert('删除重新上传', '你确定要删除印章吗？', [
                      { text: '取消', onPress: () => {} },
                      { text: '确定', onPress: this.handleDelImg },
                    ])
                  }
                />
              )}
              {files[0] && (
                <MyIcon
                  type="iconcaijianbianji"
                  style={{ position: 'absolute', right: -12, bottom: -12, zIndex: 1,fontSize:22,width:22,height:22 }}
                  onClick={() =>
                    alert('', '你要对印章进行编辑吗？', [
                      { text: '取消', onPress: () => {} },
                      { text: '确定', onPress: this.handleReCorp },
                    ])
                  }
                />
              )}

              <ImagePicker
                style={{ width: x, height: y }}
                files={files}
                onChange={this.onChange}
                onImageClick={(index, fs) => {}}
                selectable={files.length < 1}
                accept="image/gif,image/jpeg,image/jpg,image/png,image/bmp,image/tiff"
              />
            </div>
          </div>
          <div  className={styles.memo}>
                <div>支持上传10M以内的图片</div>
                <div>图片格式支持.gif,.jpg,jpeg,.png,.bmp,.tiff</div>
              </div>
          <div style={{background:'rgba(242,244,245,1)',height:'1.5vh'}}></div>
          <List style={{zIndex:2}}>
            {getFieldDecorator('name', {
              initialValue: '',
              rules: [
                {
                  required: true,
                  max:8,
                  message: '印章名称不能超过8个字符',
                },
              ],
            })(
              <InputItem clear placeholder="请输入" className={styles.formTitle} ref={el => (this.autoFocusInst = el)} onChange={this.handleInputChange}>
                <span style={{color:'red'}}>*</span>印章名称
              </InputItem>
            )}
            {sealName.length>8&&<ErrorMsg errorMsg='印章名称不能超过8个字符' />}
            {getFieldDecorator('size', {
              initialValue: '',
              rules: [
                {
                  required: true,
                  message: '印章尺寸必选！',
                },
              ],
            })(
              <Picker data={sealSize} cols={1} className="forss" onChange={this.handleSizeChange}>
                <List.Item arrow="horizontal"> <span style={{color:'red'}}>*</span>印章尺寸(宽X高)</List.Item>
              </Picker>
            )}
          </List>
          <WhiteSpace size="lg" />
        </div>
        {/* <img src={url}></img> */}
        <div  className={styles.save}>
          <Button
            type="primary"
            inline
            onClick={this.handleValidate}
            style={{}}
            loading = {loadingUpdate}

          >
            保存
          </Button>
        </div>
        <WhiteSpace />
      </div>
    );
  }
}

export default createForm()(ImagePickerExample);
